package com.example.shushiyunsst.fragment.main.home.child.icon_sst

import android.annotation.SuppressLint
import android.content.Context
import android.media.MediaRouter
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.ImageView
import android.widget.Toast
import androidx.appcompat.widget.Toolbar
import androidx.arch.core.executor.ArchTaskExecutor
import androidx.core.content.ContextCompat
import com.alibaba.android.arouter.launcher.ARouter
import com.alibaba.fastjson.JSON
import com.example.library_common.base.BaseDataBindingFragment
import com.example.library_common.base.BaseFragmentEx
import com.example.library_common.glidmodule.GlideApp
import com.example.library_common.global.AppGlobals
import com.example.library_common.networking.RestClient
import com.example.library_common.utils.ShUtils
import com.example.library_common.utils.even.ICON_TRANSFER_NOTIFY
import com.example.library_common.utils.even.MessageWrap
import com.example.library_common.utils.even.TO_REFRESH_LIST
import com.example.shushiyunsst.R
import com.example.shushiyunsst.databinding.MyOrderResultFragmentBinding

import com.example.shushiyunsst.fragment.getUserBalanceInfo
import com.example.shushiyunsst.fragment.main.constant.CURRENT_DEVICE_TOKEN
import com.example.shushiyunsst.fragment.main.home.child.icon_sst.bean.*
import com.example.shushiyunsst.util.*
import com.example.shushiyunsst.util.push.helper.PushHelper
import com.example.wallet.bean.UserInfo
import com.example.wallet.db.UserInfoManager
import com.example.wallet.utils.Preference
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.core.BasePopupView
import com.lxj.xpopup.core.ImageViewerPopupView
import com.lxj.xpopup.interfaces.SimpleCallback
import com.lxj.xpopup.interfaces.XPopupImageLoader
import org.greenrobot.eventbus.EventBus
import java.io.File

class MyOrderResultFragment : BaseDataBindingFragment<MyOrderResultFragmentBinding>(),
    View.OnClickListener {

    companion object {
        fun newInstance(toId: String): MyOrderResultFragment {
            val args = Bundle()
            args.putString("toId", toId)
            val fragment = MyOrderResultFragment()
            fragment.arguments = args
            return fragment
        }

//        var result = false

    }

    private var toId: String? = null

    private var mToolbar: Toolbar? = null

    private var mResultBean: MyOrderResultBean? = null

    private val sst = AppGlobals.getApplication().getString(R.string.wallet_sst)

    private val cml = AppGlobals.getApplication().getString(R.string.wallet_cml)

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        toId = arguments?.getString("toId")
    }


    override fun layoutId(): Int {
        return R.layout.my_order_result_fragment
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        viewBinder.onViewClick = this
        mToolbar = view.findViewById(R.id.mToolbar)

        mToolbar?.setNavigationOnClickListener { onBackPressedSupport() }

        onRequest()
    }

    private fun onRequest() {

        viewBinder.mProgressBar.visibility = View.VISIBLE

        val userInfo = UserInfoManager.userInfoManager.getUserInfoWrapper()?.userInfo
        val map = mapOf(
            "toid" to toId,
            "uid" to userInfo?.uid
        )

//        val map = mapOf(
//            "toid" to 129,
//            "uid" to 277
//        )

        RestClient.builder()
            .raw(JSON.toJSONString(map))
            .url(R.string.queryTxOrderById)
            .success {
                viewBinder.mProgressBar.visibility = View.GONE
                parseQueryTxOrder(it)

            }.failure {
                Toast.makeText(_mActivity, "获取订单详情失败", Toast.LENGTH_SHORT).show()
                onBackPressedSupport()
            }.error { _, msg ->
                Toast.makeText(_mActivity, msg, Toast.LENGTH_SHORT).show()
                onBackPressedSupport()
            }.build().post()
    }

    private fun parseQueryTxOrder(it: String?) {
        mResultBean = JSON.parseObject(it, MyOrderResultBean::class.java)
        viewBinder.bean = mResultBean

        val result =
            mResultBean?.order?.orderStatus == PAYED_WAITING || mResultBean?.order?.orderStatus == TRANSFER_OVER
//        R.drawable.ic_baseline_help_24
        val icon = when (mResultBean?.order?.orderStatus) {
            ON_PAYING -> R.drawable.ic_baseline_help_24
            BUYER_CANCELED, SELLER_CANCELED -> R.drawable.ic_round_order_cancel_24
            TRANSFER_OVER, PAYED_WAITING -> R.drawable.ic_order_done
            else -> R.drawable.ic_baseline_help_24
        }
//        val icon = if (result) R.drawable.ic_order_done else R.drawable.ic_round_order_cancel_24
        val iconColor = if (result) R.color.PrimaryColor else R.color.image_color_red
        viewBinder.icon.setImageResource(icon)

        viewBinder.icon.setColorFilter(ContextCompat.getColor(_mActivity, iconColor))

        viewBinder.resTv.text = mResultBean?.order?.orderDesc

        val tokenType = mResultBean?.order?.tokenType
        val pageTitle = if (mResultBean?.order?.isSeller == 1) "卖($tokenType)" else "买($tokenType)"

//        val pageTitleColor = if (mResultBean?.order?.isSeller == 1) R.color.image_color_red else R.color.PrimaryColor


        mToolbar?.title = "$pageTitle ${mResultBean?.order?.orderDesc}"
//        mToolbar?.setTitleTextColor(ContextCompat.getColor(_mActivity, pageTitleColor))

        showByTokenType()


        when (mResultBean?.order?.orderStatus) {
            ON_PAYING -> {
                viewBinder.fanBi.visibility = View.GONE

                viewBinder.orderInfo.visibility = View.INVISIBLE

                viewBinder.toComplaint.visibility = View.GONE

                viewBinder.paymentTv.text = "支付方式"

                if (mResultBean?.order?.isSeller == 0) {

                    viewBinder.fanBi.visibility = View.VISIBLE

                    viewBinder.orderInfo.visibility = View.VISIBLE

                    viewBinder.fanBi.setText(R.string.pay_off)
                }


                val drawable =
                    ContextCompat.getDrawable(_mActivity, R.drawable.ic_round_album_arrow_right_24)
                if (drawable != null) {
                    val mDrawable = ShUtils.tintDrawable(
                        drawable,
                        ContextCompat.getColor(_mActivity, R.color.bg_color_6)
                    )
                    mDrawable.setBounds(0, 0, mDrawable.intrinsicWidth, mDrawable.intrinsicHeight)
                    viewBinder.paymentTv.setCompoundDrawables(null, null, mDrawable, null)
                }
            }
            PAYED_WAITING -> {
                viewBinder.fanBi.visibility = View.GONE

                viewBinder.orderInfo.visibility = View.VISIBLE

//                viewBinder.toComplaint.visibility = View.VISIBLE
                showByTokenType()

                if (mResultBean?.order?.isSeller == 1) {

                    viewBinder.fanBi.visibility = View.VISIBLE

                    viewBinder.fanBi.text = "放币"
                }

                viewBinder.paymentTv.text = "付款信息"

                viewBinder.paymentTv.setCompoundDrawables(null, null, null, null)
            }
            ARGUMENT -> {
                showByTokenType()
//                viewBinder.toComplaint.visibility = View.VISIBLE
            }
            else -> {
                viewBinder.fanBi.visibility = View.GONE

                viewBinder.paymentTv.text = "付款信息"

                viewBinder.paymentTv.setCompoundDrawables(null, null, null, null)

                viewBinder.orderInfo.visibility = View.VISIBLE
            }
        }


        showPay()
    }

    private fun showByTokenType() {
        when(mResultBean?.order?.tokenType){
            sst->{
                viewBinder.toComplaint.visibility = View.VISIBLE
            }
            cml->{
                viewBinder.toComplaint.visibility = View.GONE
                viewBinder.tipTv.visibility=View.GONE
            }
        }
    }

    private fun handPay() {
        if (mResultBean?.order?.orderStatus == ON_PAYING && mResultBean?.order?.isSeller == 0) {

            when (mResultBean?.order?.payType) {
                A_LI_PAY -> {
                    if (mResultBean?.payment?.isSupportWx == 1) {
                        mResultBean?.order?.payType = WEI_CHAT_PAY
                    } else if (mResultBean?.payment?.isSupportBank == 1) {
                        mResultBean?.order?.payType = BANK_PAY
                    }

                }
                WEI_CHAT_PAY -> {
                    if (mResultBean?.payment?.isSupportBank == 1) {
                        mResultBean?.order?.payType = BANK_PAY
                    } else if (mResultBean?.payment?.isSupportAipay == 1) {
                        mResultBean?.order?.payType = A_LI_PAY
                    }

                }
                BANK_PAY -> {
                    if (mResultBean?.payment?.isSupportAipay == 1) {
                        mResultBean?.order?.payType = A_LI_PAY
                    } else if (mResultBean?.payment?.isSupportWx == 1) {
                        mResultBean?.order?.payType = WEI_CHAT_PAY
                    }

                }
            }

            showPay()
        }

    }

    private fun showPay() {
        viewBinder.aliPayLayout.visibility = View.GONE
        viewBinder.weiChatPayLayout.visibility = View.GONE
        viewBinder.bankCardPayLayout.visibility = View.GONE
        val payment = mResultBean?.payment

        if(payment==null){
            viewBinder.paymentLayout.visibility= View.GONE
            return
        }
        when (mResultBean?.order?.getPayTypeUI(mResultBean?.payment)) {
            A_LI_PAY -> {
                if (mResultBean?.payment?.isSupportAipay == 1) {
                    viewBinder.aliPayLayout.visibility = View.VISIBLE
                    viewBinder.weiChatPayLayout.visibility = View.GONE
                    viewBinder.bankCardPayLayout.visibility = View.GONE
                }

            }
            WEI_CHAT_PAY -> {
                if (mResultBean?.payment?.isSupportWx == 1) {
                    viewBinder.aliPayLayout.visibility = View.GONE
                    viewBinder.weiChatPayLayout.visibility = View.VISIBLE
                    viewBinder.bankCardPayLayout.visibility = View.GONE
                }

            }
            BANK_PAY -> {
                if (mResultBean?.payment?.isSupportBank == 1) {
                    viewBinder.aliPayLayout.visibility = View.GONE
                    viewBinder.weiChatPayLayout.visibility = View.GONE
                    viewBinder.bankCardPayLayout.visibility = View.VISIBLE
                }

            }
            else -> {
                viewBinder.aliPayLayout.visibility = View.GONE
                viewBinder.weiChatPayLayout.visibility = View.GONE
                viewBinder.bankCardPayLayout.visibility = View.GONE
                viewBinder.paymentTv.text = "请添加收款信息"
            }
        }
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.paymentTv -> {
                if (mResultBean?.order?.orderStatus == ON_PAYING) {
                    if ((mResultBean?.order?.payType ?: -100) < 0) {
                        ARouter.getInstance().build(ADD_PAYING_WAY).startNavigation(this)
                    } else {

                        handPay()
                    }
                }
            }
            R.id.to_complaint -> {
//                val userInfo = UserInfoManager.userInfoManager.getUserInfoWrapper()?.userInfo

//                if (userInfo?.uid==mResultBean.order.)
//                if (mResultBean?.order?.isSeller == 1) {
//                    sellerComplaint()
//                    return
//                }
                ARouter.getInstance()
                    .build(COMPLAINT)
                    .withString(TO_ID, mResultBean?.order?.toid.toString())
                    .startNavigation(this)
            }
            R.id.fanBi -> {
                when (mResultBean?.order?.orderStatus) {
                    ON_PAYING -> {
                        if (mResultBean?.order?.isSeller == 0) {
                            onPayed()
                        }

                    }
                    PAYED_WAITING -> {
                        if (mResultBean?.order?.isSeller == 1) {
                            fanBi()
                        }

                    }
                }
            }
            R.id.bankCardPayBankNo -> {
                clipboard("bankCardPayBankNo", mResultBean?.payment?.bankNo ?: "")
            }

            R.id.bankCardPayRealName -> {
                clipboard("bankCardPayRealName", mResultBean?.payment?.realName ?: "")
            }

            R.id.bankCardPayBankNameChild -> {
                clipboard("bankCardPayBankNameChild", mResultBean?.payment?.bankNameChild ?: "")
            }

            R.id.bankCardPayBankName -> {
                clipboard("bankCardPayBankNameChild", mResultBean?.payment?.bankName ?: "")
            }

            R.id.weiChatPayAccount -> {
                clipboard("weiChatPayAccount", mResultBean?.payment?.wxAccount ?: "")
            }

            R.id.weiChatPayRealName -> {
                clipboard("weiChatPayRealName", mResultBean?.payment?.realName ?: "")
            }

            R.id.aliPayAccount -> {
                clipboard("aliPayAccount", mResultBean?.payment?.alipayAccount ?: "")
            }

            R.id.aliPayRealName -> {
                clipboard("aliPayAccount", mResultBean?.payment?.realName ?: "")
            }

            R.id.aliPayPic -> {
                val imageViewerPopupView = ImageViewerPopupView(_mActivity)
                imageViewerPopupView.setImageUrls(listOf(mResultBean?.payment?.alipayUrl))
                imageViewerPopupView.setXPopupImageLoader(object : XPopupImageLoader {
                    override fun loadImage(position: Int, uri: Any, imageView: ImageView) {
                        GlideApp.with(this@MyOrderResultFragment)
                            .load(uri)
                            .centerInside()
                            .into(imageView)
                    }

                    override fun getImageFile(context: Context, uri: Any): File {
                        return File(uri.toString())
                    }
                })
                XPopup.Builder(_mActivity)
                    .asCustom(imageViewerPopupView)
                    .show()
            }

            R.id.weiChatPayPic -> {
                val imageViewerPopupView = ImageViewerPopupView(_mActivity)
                imageViewerPopupView.setImageUrls(listOf(mResultBean?.payment?.wxUrl))
                imageViewerPopupView.setXPopupImageLoader(object : XPopupImageLoader {
                    override fun loadImage(position: Int, uri: Any, imageView: ImageView) {
                        GlideApp.with(this@MyOrderResultFragment)
                            .load(uri)
                            .centerInside()
                            .into(imageView)
                    }

                    override fun getImageFile(context: Context, uri: Any): File {
                        return File(uri.toString())
                    }
                })
                XPopup.Builder(_mActivity)
                    .asCustom(imageViewerPopupView)
                    .show()
            }

        }
    }

    private fun sellerComplaint() {
        val userInfo = UserInfoManager.userInfoManager.getUserInfoWrapper()?.userInfo
        val map = mapOf(
            "payUrl" to "",
            "toid" to mResultBean?.order?.toid,
            "uid" to userInfo?.uid
        )
        RestClient.builder()
            .raw(JSON.toJSONString(map))
            .url(R.string.orderAppeal)
            .success {
                Toast.makeText(_mActivity, "发送成功", Toast.LENGTH_LONG).show()
                onRequest()
            }.failure {

                Toast.makeText(_mActivity, "发送失败", Toast.LENGTH_LONG).show()
            }.error { _, msg ->

                Toast.makeText(_mActivity, msg, Toast.LENGTH_LONG).show()
            }.build().post()
    }

    private fun onPayed() {
        XPopup.Builder(_mActivity)
            .asCustom(
                CurrencyTransferBuyStatusPop(_mActivity)
                    .setBean(mResultBean)
                    .setCallBackListener(object :
                        CurrencyTransferBuyStatusPop.CallBackListener {
                        override fun sureAction() {

                            val map = mapOf(
                                "payType" to mResultBean?.order?.payType,
                                "toid" to mResultBean?.order?.toid
                            )

                            RestClient.builder()
                                .raw(JSON.toJSONString(map))
                                .url(R.string.saveTxBuyOrderPay)
                                .success {

                                    parseSaveTxBuyOrderPay(it)
                                }
                                .failure {
                                    Toast.makeText(_mActivity, "发送订单失败", Toast.LENGTH_SHORT).show()
                                    onBackPressedSupport()
                                }.error { _, msg ->
                                    Toast.makeText(_mActivity, msg, Toast.LENGTH_SHORT).show()
                                    onBackPressedSupport()
                                }
                                .build().post()

                        }

                    })
            )
            .show()

    }


    private fun parseSaveTxBuyOrderPay(it: String?) {
        val obj = JSON.parseObject(it, SaveTxBuyOrderPayBean::class.java)
        pushMsg(obj)
        startWithPop(CollectedCoinsFragment.newInstance("${obj.order.toid}"))
    }

    @SuppressLint("RestrictedApi")
    private fun pushMsg(obj: SaveTxBuyOrderPayBean?) {
        ArchTaskExecutor.getIOThreadExecutor().execute {
            try {
                val deviceTokens = obj?.pushMsg?.deviceToken ?: ""
//                val deviceTokens = Preference.HOLDER.getCustomAppProfile(CURRENT_DEVICE_TOKEN)
                obj?.pushMsg?.type = FU_KUANG
                obj?.pushMsg?.orderId = obj?.order?.txNo
                val pushHelper = PushHelper()
                val broadcast = PushHelper.getAndroidBroadcast()
                broadcast.setTitle("SST放款")
                broadcast.setDeviceToken(deviceTokens)
                broadcast.setPlaySound(true)
                broadcast.setTicker("SST放款")
                broadcast.setTitle("SST放款")
                broadcast.setText("${obj?.pushMsg?.contentDesc}")
                broadcast.setCustomField(JSON.toJSONString(obj?.pushMsg))
                pushHelper.sendAndroidBroadcast(broadcast)
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }

    private fun fanBi() {
        val mPop = PayingPassWordVerifyPop(_mActivity)
        XPopup.Builder(_mActivity)
            .setPopupCallback(object : SimpleCallback() {
                override fun onDismiss(popupView: BasePopupView?) {
                    super.onDismiss(popupView)
                    if (mPop.getIsOnVerifyPop()) {
                        if (mPop.getVerifyPop()) {
                            handFanBi()
                        } else {
                            Toast.makeText(_mActivity, "支付密码错误", Toast.LENGTH_SHORT).show()
                        }
                    }
                }
            })
            .asCustom(mPop)
            .show()
    }

    private fun handFanBi() {
        val userInfo =
            UserInfoManager.userInfoManager.getUserInfoWrapper()?.userInfo

        val map = mapOf(
            "toid" to mResultBean?.order?.toid,
            "uid" to userInfo?.uid
        )


        RestClient.builder()
            .raw(JSON.toJSONString(map))
            .url(R.string.updateTxOrder)
            .success {
                parseUpdateTxOrder(it)
            }.failure {
                Toast.makeText(_mActivity, "发送失败", Toast.LENGTH_SHORT).show()
            }.error { _, msg ->
                Toast.makeText(_mActivity, msg, Toast.LENGTH_SHORT).show()
            }.build().post()
    }

    private fun parseUpdateTxOrder(it: String?) {
        val obj = JSON.parseObject(it, UpdateTxOrderBean::class.java)
        fanBiPushMsg(obj)
        Toast.makeText(_mActivity, "发送成功", Toast.LENGTH_SHORT).show()
        EventBus.getDefault().post(MessageWrap.getInstance(TO_REFRESH_LIST))
        getUserBalanceInfo(AppGlobals.getApplication())
        onBackPressedSupport()
    }

    @SuppressLint("RestrictedApi")
    private fun fanBiPushMsg(obj: UpdateTxOrderBean) {
        ArchTaskExecutor.getIOThreadExecutor().execute {
            try {
                obj.pushMsg.type = FAN_BI
                obj.pushMsg.orderId = obj.order.txNo
                val deviceTokens = obj.pushMsg.deviceToken
                val userInfo = UserInfoManager.userInfoManager.getUserInfoWrapper()?.userInfo
                val pushHelper = PushHelper()
                val broadcast = PushHelper.getAndroidBroadcast()
                broadcast.setTitle("SST放币")
                broadcast.setDeviceToken(deviceTokens)
                broadcast.setPlaySound(true)
                broadcast.setTicker("SST放币")
                broadcast.setCustomField(JSON.toJSONString(obj.pushMsg))
                broadcast.setTitle("${userInfo?.nickName} 向你放出 ${obj.order?.totalPrice} 个 SSL")
                broadcast.setText("${userInfo?.nickName} 向你放出 ${obj.order?.totalPrice} 个 SSL")

                pushHelper.sendAndroidBroadcast(broadcast)
            } catch (e: Exception) {
                e.printStackTrace()
            }


        }
    }

    override fun handMessage(msg: MessageWrap?) {
//        super.handMessage(msg)
        if (msg?.message == ICON_TRANSFER_NOTIFY) {
            onRequest()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        val iconPushMsgList = PushMsgManager.getInstance().iconPushMsgList
        var index = -10
        for (i in 0 until iconPushMsgList.size) {
            val pushMsgBean = iconPushMsgList[i]
            if (pushMsgBean.orderId == mResultBean?.order?.txNo) {
                index = i
                break
            }
        }

        if (index >= 0) {
            val pushMsgBean = iconPushMsgList[index]
            iconPushMsgList.removeAt(index)
            iconPushMsgList.remove(pushMsgBean)
        }
        EventBus.getDefault().post(MessageWrap.getInstance(ICON_TRANSFER_NOTIFY))
    }


}